﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;

namespace YGD.Generic
{
    public static class Extensions
    {
        public static T O<T>(this T source) where  T:new()
        {
            Console.Write(source);
            return source;
        }
        public static T OL<T>(this T source)
        {
            Console.WriteLine(source);
            return source;
        }
    }

    public static class StringExt
    {
    
        public static string CutString(this string source,int length)
        {
            if (source.Length <= length) return source;

            return source.Substring(0, length);
        }

        public static string GetRegexMatch(this string source, string regexString)
        {
            var regex = new Regex(regexString);
            Match match = regex.Match(source);
            if (match.Success)
                return match.Value;
            return string.Empty;
        }

        public static List<string> GetRegexMatchCollection(this string source, string regexString)
        {
            var regex = new Regex(regexString);
            var matchCoollection = regex.Matches(source);
            var result = new List<string>();
            for (int i = 0; i < matchCoollection.Count; i++)
            {
                result.Add(matchCoollection[i].Value);
            }

            return result;
        }
    }


    public static class DateTimeExt
    {
        public static DateTime JavascriptDateTimeToCSharpDateTime(this string source)
        {
            DateTime resultValue;
            DateTime.TryParseExact(source, "ddd MMM dd HH:mm:ss +0800 yyyy", new CultureInfo("en-us"), DateTimeStyles.RoundtripKind, out resultValue);

            return resultValue;
        }

        public static bool ToDateTime(this string source,string format,out DateTime resultValue)
        {
            if(DateTime.TryParseExact(source, format, new CultureInfo("en-us"), DateTimeStyles.RoundtripKind, out resultValue))
                return false;
            return true;
        }


        public static DateTime GetSunday(this DateTime source)
        {
            return source.AddDays(-(int) source.DayOfWeek);
        }
    }
}
